package com.zkingsoft.command;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
 * 生成Command实例对象
 * @author shushine
 *
 */
public class CommandFactory {

	private static CommandFactory factory = null;
	
	//封装Command配置信息
	private Properties props  = null;
	
	//封装Command对象key:请求名,Value:Command实例对象
	private Map<String,Command> commands = null;
	
	private CommandFactory() {
		props = new Properties();
		commands = new HashMap<String,Command>();
		
		initProperties();
	}
	
	private void initProperties() {
		InputStream input = CommandFactory.class.getResourceAsStream("/command.properties");
		
		Properties props = new Properties();
		try {
			props.load(input);
			this.props = props;
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	
	public synchronized static CommandFactory newInstance() {
		if(factory == null) {
			factory = new CommandFactory();
		}
		return factory;
	}
	
	public Command getCommand(String key) {
		Command command = null;
		synchronized(this) {
			command = commands.get(key);
			if(command == null) {
				String className = props.getProperty(key);
				try {
					command = (Command)Class.forName(className).newInstance();
					commands.put(key, command);
				} catch (InstantiationException e1) {
					e1.printStackTrace();
				} catch (IllegalAccessException e1) {
					e1.printStackTrace();
				} catch (ClassNotFoundException e1) {
					e1.printStackTrace();
				}
			}
		}
		return command;
	}
}
